package com.cxs.commoneventtest.slice;

import com.cxs.commoneventtest.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.event.commonevent.*;
import ohos.rpc.RemoteException;

public class MainAbilitySlice extends AbilitySlice {
    // 自定义公共事件的名称
    static final String EVENT_ACTION = "com.cxs.commoneventtest.event";

    static final String INTENT_PARAM_KEY = "intent.param.key";
    static boolean isSubscribe = false;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        findComponentById(ResourceTable.Id_text_helloworld).setClickedListener(this::subscribe);
    }

    private void subscribe(Component component) {
            if (isSubscribe) {
                return;
            }
            MatchingSkills matchingSkills = new MatchingSkills();
            matchingSkills.addEvent(EVENT_ACTION);
            CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
            CommonEventSubscriber subscriber = new CommonEventSubscriber(subscribeInfo) {
                @Override
                public void onReceiveEvent(CommonEventData commonEventData) {
                    Intent intent = commonEventData.getIntent();
                    int intParam = intent.getIntParam(INTENT_PARAM_KEY, -1);
                    System.out.println("onReceiveEvent:" + intParam);
                }
            };
            try {
                // 订阅公共事件
                CommonEventManager.subscribeCommonEvent(subscriber);
                isSubscribe = true;
                System.out.println("订阅公共事件成功！");
            } catch (RemoteException e) {
                e.printStackTrace();
            }


    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
